package com.czy.seed.mvc.home.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.base.service.impl.BaseServiceImpl;
import com.czy.seed.mvc.home.controller.PurchaseController;
import com.czy.seed.mvc.home.entity.Quotation;
import com.czy.seed.mvc.home.entity.QuoteOrCompare;

import com.czy.seed.mvc.home.mapper.QuoteOrCompareMapper;

import com.czy.seed.mvc.home.service.QuotationService;
import com.czy.seed.mvc.home.service.QuoteOrCompareService;
import com.czy.seed.mvc.sys.service.SysUserService;
import com.czy.seed.mvc.util.ManageSendMessage;
import com.czy.seed.mvc.util.PrincipalUtil;
import com.czy.seed.mvc.util.SystemProperties;
import com.czy.seed.mybatis.base.QueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class QuoteOrCompareImpl extends BaseServiceImpl<QuoteOrCompare> implements QuoteOrCompareService {

    @Autowired
    private QuoteOrCompareMapper quoteOrCompareMapper;
    @Autowired
    private QuoteOrCompareService quoteOrCompareService;

    @Autowired
    private SysUserService sysUserService;


    @Autowired
    private QuotationService quotationService;
    @Autowired
    SystemProperties systemProperties;
    public static Logger logger = LoggerFactory.getLogger(PurchaseController.class);

    @Override
    public void updateQuotationNumber(Long id, Long c_userid) {
        quoteOrCompareMapper.updateQuotationNumber(id, c_userid);
    }


    @Override
    public void updateQuotationOrCompaer(Long id, Long type, long c_userid) {
        quoteOrCompareMapper.updateQuotationOrCompaer(id, type, c_userid);
    }

    @Override
    public Map<String, Object> addQuoteOrCompare_impl(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String ord = request.getParameter("QuoteOrCompare");
        try {
            QuoteOrCompare quoteOrCompare = JSONObject.parseObject(ord, QuoteOrCompare.class);
            quoteOrCompare.setInitiatorId(PrincipalUtil.getLoginUser().getId());
            quoteOrCompare.setPurchaseUnit(PrincipalUtil.getLoginUser().getName());
            quoteOrCompare.setType(0);
            quoteOrCompare.setNumber(uuid);
            quoteOrCompare.setCreationTime(new Date());
            int i = quoteOrCompareService.insert(quoteOrCompare);
            pageInfo.put("addLin", i);
        } catch (Exception e) {
            throw new RuntimeException("添加竞价，询价单失败");
        }
        return pageInfo;
    }

    @Override
    @Transactional
    public Map<String, Object> addQuoteAndCompare_impl(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String ord = request.getParameter("QuoteOrCompare");
        //商家信息
        String merchant = request.getParameter("merchants");
        String[] merchants = merchant.split("-");
        try {
            QuoteOrCompare QuoteOrCompare = JSONObject.parseObject(ord, QuoteOrCompare.class);
            QuoteOrCompare.setInitiatorId(PrincipalUtil.getLoginUser().getId());
            QuoteOrCompare.setPurchaseUnit(PrincipalUtil.getLoginUser().getName());
            QuoteOrCompare.setType(0);
            QuoteOrCompare.setNumber(uuid);
            QuoteOrCompare.setCreationTime(new Date());
            int i = quoteOrCompareService.insert(QuoteOrCompare);
            //询价单ID
            long quo_id = QuoteOrCompare.getId();
            //根据商家ID增加商家报价单
            String context = "您有一个采购询价单需要报价，请您尽快处理！";
            for (int k = 0; k < merchants.length; k++) {
                //增加merchants.length条报价数据
                Quotation qt = new Quotation();
                qt.setQuoteOrCompareId(quo_id);
                qt.setMerchantId(Long.parseLong(merchants[k]));
                qt.setName(QuoteOrCompare.getCommodityName());
                qt.setType(0);
                qt.setQuoteTime(new Date());
                qt.setCreatetime(new Date());
                quotationService.insert(qt);
                try {
                    new ManageSendMessage().queryMessage("商家", Long.parseLong(merchants[k]), context, sysUserService, systemProperties);
                } catch (Exception e) {
                    logger.error("给商家发送短信出错：{}", e.getMessage());
                }

            }
            pageInfo.put("addLin", i);
            pageInfo.put("status", "true");
        } catch (Exception e) {
            logger.error("添加报价单失败", e);
        }
        return pageInfo;
    }

    @Override
    public List<QuoteOrCompare> selectAll(Long type) {
        return quoteOrCompareMapper.selectAll(type);
    }

    /**
     * 根据采购清单ID更新询价单及其报价单类型
     * 当采购单位再次询价的时候如果上一次询价还没有结束，首先要关闭上次询价，然后再次询价
     * 不允许连续询价,更新询价单和报价单状态为2  取消报价
     */
    @Override
    public Map<String, Object> uodateTypeAll(long id) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        QueryParams queryParams = new QueryParams(QuoteOrCompare.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("purchaseId", id);
        criteria.andNotEqualTo("type", 2);
        QuoteOrCompare quoteOrCompare = quoteOrCompareService.selectOneByParams(queryParams);
        if (quoteOrCompare != null) {
            quoteOrCompare.setType(2);
            long q_id = quoteOrCompare.getId();
            QueryParams queryParams1 = new QueryParams(Quotation.class);
            QueryParams.Criteria criteria1 = queryParams1.createCriteria();
            criteria1.andEqualTo("quoteOrCompareId", q_id);
            Quotation quotation = quotationService.selectOneByParams(queryParams1);
            quotation.setType(2);
            quoteOrCompareService.updateByPrimaryKey(quoteOrCompare);
            quotationService.updateByPrimaryKey(quotation);
            pageInfo.put("message", "更新成功");
        } else {
            pageInfo.put("message", "没有所需要关闭的历史询价单");
        }
        return pageInfo;
    }
}
